package com.ht.file.controller;

import cn.hutool.core.io.FileUtil;
import com.ht.common.core.domain.R;
import com.ht.common.core.utils.StringUtils;
import com.ht.common.core.utils.sign.Base64;
import com.ht.common.core.web.domain.AjaxResult;
import com.ht.common.security.annotation.InnerAuth;
import com.ht.file.api.dto.SysFileDto;
import com.ht.file.constant.FileType;
import com.ht.file.domain.SysAttachFile;
import com.ht.file.service.ISysFileService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

;

/**
 * 文件请求处理
 *
 * @author ruoyi
 */
@RestController
public class SysFileController {
    private static final Logger log = LoggerFactory.getLogger(SysFileController.class);

    @Autowired
    private ISysFileService sysFileService;

    /**
     * 上传文件存储在本地的根路径
     */
    @Value("${file.path}")
    private String localFilePath;

    @Value("${file.domain}")
    private String domain;

    @Value("${file.prefix}")
    private String prefix;

    public ResponseEntity<FileSystemResource> export(File file) {
        if (file == null) {
            return null;
        }
        HttpHeaders headers = new HttpHeaders();
        String fileExtName = FileUtil.extName(file.getName());
        String mediaType = MediaType.APPLICATION_OCTET_STREAM_VALUE;
        if (FileType.IMGS.contains(fileExtName.toUpperCase())) {
            mediaType = MediaType.IMAGE_PNG_VALUE;
        } else if (FileType.PDFS.contains(fileExtName.toUpperCase())) {
            mediaType = MediaType.APPLICATION_PDF_VALUE;
        } else {
            headers.add("Content-Disposition", "attachment; filename=" + file.getName());
            headers.add("Cache-Control", "no-cache, no-store, must-revalidate");
            headers.add("Pragma", "no-cache");
            headers.add("Expires", "0");
            headers.add("Last-Modified", new Date().toString());
            headers.add("ETag", String.valueOf(System.currentTimeMillis()));
        }
        return ResponseEntity
                .ok()
                .headers(headers)
                .contentLength(file.length())
                .contentType(MediaType.parseMediaType(mediaType))
                .body(new FileSystemResource(file));
    }


    /**
     * 文件上传请求
     */
    @PostMapping("/upload")
    public AjaxResult upload(MultipartFile file) {
        try {
            SysAttachFile sysFile = sysFileService.uploadFile(file);
            Map<String,Object> resMap = new HashMap<>();
            resMap.put("fileName", sysFile.getFilename());
            resMap.put("originName", sysFile.getOriginName());
            resMap.put("suffix", sysFile.getExtName());
            resMap.put("fileSize", sysFile.getSize());
            resMap.put("url", sysFile.getUrl());
            return AjaxResult.success(resMap);
        } catch (Exception e) {
            log.error("上传文件失败", e);
            return AjaxResult.error();
        }
    }



    @GetMapping(value = "/viewFile/{filename}")
    public ResponseEntity<FileSystemResource> viewFile(@PathVariable("filename") String filename) {
        if (StringUtils.isBlank(filename)) {
            return null;
        }
        log.info("浏览文件:{}", filename);
        SysAttachFile saf = sysFileService.selectSysAttachFileByFilename(filename);
        if (null == saf) {
            return null;
        }
        String filePath=localFilePath + File.separator + saf.getYmdDir() + File.separator + saf.getFilename();
        log.info("浏览文件:{}", filePath);
        return export(new File(filePath));
    }




    @InnerAuth
    @PostMapping(value = "/getFileBase64Data/{fileId}")
    public R<SysFileDto> getFileBase64Data(@PathVariable("fileId") String fileId){
        SysAttachFile saf = sysFileService.selectSysAttachFileByFilename(fileId);
        if (null == saf) {
            return R.fail("文件不存在");
        }
        String filePath=localFilePath + File.separator + saf.getYmdDir() + File.separator + saf.getFilename();
        byte[] data=  FileUtil.readBytes(new File(filePath));
        SysFileDto sdf=new SysFileDto();
        sdf.setFileData(Base64.encode(data));
        sdf.setFileId(saf.getFilename());
        sdf.setName(saf.getOriginName());
        sdf.setSuffix(saf.getExtName());
        return R.ok(sdf);
    }

    @InnerAuth
    @PostMapping(value = "/getFileHttpUrl/{fileId}")
    public R<SysFileDto> getFileHttpUrl(@PathVariable("fileId") String fileId){
        SysAttachFile saf = sysFileService.selectSysAttachFileByFilename(fileId);
        if (null == saf) {
            return R.fail("文件不存在");
        }
        String httpUrl=domain + prefix + "/" + saf.getYmdDir() +"/"+ saf.getFilename();
        SysFileDto sdf=new SysFileDto();
        sdf.setFileId(saf.getFilename());
        sdf.setName(saf.getOriginName());
        sdf.setSuffix(saf.getExtName());
        sdf.setFileUrl(httpUrl);
        return R.ok(sdf);
    }




}
